package pattern.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.util.TypeUtils;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import pattern.SmsServiceTool;
import pattern.annontations.Menu;
import pattern.annontations.Secure;
import pattern.email.EmailSendTool;
import pattern.email.SendEmailModel;
import pattern.exception.AssertTool;
import pattern.result.ResponseData;
import pattern.routing.WorkSmsApiRouting;

/**
 * @author Simon
 * @date 2020-08-21
 */
@Api(tags = "邮件相关接口")
@ApiSort(4)
@RestController
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Secure
@Slf4j
@RequestMapping(WorkSmsApiRouting.Email.BASE)
@Menu(menuName = "email", menuUri = "email", foundational = false)
public class EmailController {

    private final EmailSendTool emailSendTool;

    @ApiOperation(value = "发送验证码")
    @GetMapping(WorkSmsApiRouting.Email.SEND_CODE)
    @Secure(value = -1,actionUri = "email:send", actionName = "send", actionNote = "email")
    public ResponseData<Boolean> sendCode(String address,@ApiParam(value="语言：默认中文 en:英文") @RequestParam(required = false)String type) {
        AssertTool.isTrue(EmailValidator.getInstance().isValid(address), "邮箱格式错误");
        //存入缓存
        var code = RandomUtil.randomInt(1000,10000);
        if (this.check(address)) {
            return new ResponseData<>(Boolean.FALSE);
        }
        SmsServiceTool.getMsgCache().code.put(address, String.valueOf(code));
        SendEmailModel sendEmailModel=new SendEmailModel();
        sendEmailModel.setAddress(address);
        sendEmailModel.setName(address);
        sendEmailModel.setContent(getEmail(TypeUtils.castToString(code), type));
        emailSendTool.send(sendEmailModel);
        SmsServiceTool.getMsgCache().sendTime.put(address, new DateTime());
        return new ResponseData<>(Boolean.TRUE);
    }

    @ApiOperation(value = "验证验证码")
    @GetMapping(WorkSmsApiRouting.Email.CHECK_CODE)
    @Secure(value = -1)
    public ResponseData<Boolean> checkCode(@RequestParam("address") String address, @RequestParam("code") String code) {
        var data = SmsServiceTool.getMsgCache().code.GET(address);
        if (data.isSuccess()) {
            if (data.getValue().equals(code)) {
                return new ResponseData<>(Boolean.TRUE);
            }
        }

        return new ResponseData<>(Boolean.FALSE);
    }

    /**
     * 校验30s有无发送短信
     */
    private boolean check(String address) {
        var data = SmsServiceTool.getMsgCache().sendTime.GET(address);
        if (data.isSuccess()) {
            var between = DateUtil.between(data.getValue(), new DateTime(), DateUnit.SECOND);
            if (between <= 30L) {
                log.warn("30s内有发送邮件无法重新发送{}", address);
                //小于等于30
                return true;
            }
        }
        return false;
    }


    public String getEmail(String code,String type){
        if("en".equals(type)){
            return """
                <head>
                    <base target="_blank" />
                    <style type="text/css">::-webkit-scrollbar{ display: none; }</style>
                    <style id="cloudAttachStyle" type="text/css">#divNeteaseBigAttach, #divNeteaseBigAttach_bak{display:none;}</style>
                    <style id="blockquoteStyle" type="text/css">blockquote{display:none;}</style>
                    <style type="text/css">
                        body{font-size:14px;font-family:arial,verdana,sans-serif;line-height:1.666;padding:0;margin:0;overflow:auto;white-space:normal;word-wrap:break-word;min-height:100px}
                        td, input, button, select, body{font-family:Helvetica, 'Microsoft Yahei', verdana}
                        pre {white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space:-o-pre-wrap;word-wrap:break-word;width:95%}
                        th,td{font-family:arial,verdana,sans-serif;line-height:1.666}
                        img{ border:0}
                        header,footer,section,aside,article,nav,hgroup,figure,figcaption{display:block}
                        blockquote{margin-right:0px}
                    </style>
                </head>
                <body tabindex="0" role="listitem">
                <table width="700" border="0" align="center" cellspacing="0" style="width:700px;">
                    <tbody>
                    <tr>
                        <td>
                            <div style="width:700px;margin:0 auto;border-bottom:1px solid #ccc;margin-bottom:30px;">
                                <table border="0" cellpadding="0" cellspacing="0" width="700" height="39" style="font:12px Tahoma, Arial, 宋体;">
                                    <tbody><tr><td width="210"></td></tr></tbody>
                                </table>
                            </div>
                            <div style="width:680px;padding:0 10px;margin:0 auto;">
                                <div style="line-height:1.5;font-size:14px;margin-bottom:25px;color:#4d4d4d;">
                                    <strong style="display:block;margin-bottom:15px;">Dear user：<span style="color:#f60;font-size: 16px;"></span>Hello！</strong>
                                    <strong style="display:block;margin-bottom:15px;">
                                        You are working on <span style="color: red">verify</span>operate，Enter the verification code in the input box：<span style="color:#f60;font-size: 24px">"""+code+
                    """
                    </span>，To complete the operation。
                                        </strong>
                                    </div>
                                    <div style="margin-bottom:30px;">
                                        <small style="display:block;margin-bottom:20px;font-size:12px;">
                                            <p style="color:#747474;">
                                                Note: This operation may change your password, login email address or bound mobile phone.  If you do not perform this operation by yourself, log in to the system and change the password to ensure account security 
                                                <br>（The staff will not ask you for this verification code, please do not leak!)
                                            </p>
                                        </small>
                                    </div>
                                </div>
                                <div style="width:700px;margin:0 auto;">
                                    <div style="padding:10px 10px 0;border-top:1px solid #ccc;color:#747474;margin-bottom:20px;line-height:1.3em;font-size:12px;">
                                        <p>Please do not reply to this system email<br>
                                            Please take good care of your email to prevent your account from being stolen by others
                                        </p>
                                        <p>Pattern Technology Co.,Ltd</p>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        </tbody>
                    </table>
                    </body>
                    """;
        }else{
            return """
                <head>
                    <base target="_blank" />
                    <style type="text/css">::-webkit-scrollbar{ display: none; }</style>
                    <style id="cloudAttachStyle" type="text/css">#divNeteaseBigAttach, #divNeteaseBigAttach_bak{display:none;}</style>
                    <style id="blockquoteStyle" type="text/css">blockquote{display:none;}</style>
                    <style type="text/css">
                        body{font-size:14px;font-family:arial,verdana,sans-serif;line-height:1.666;padding:0;margin:0;overflow:auto;white-space:normal;word-wrap:break-word;min-height:100px}
                        td, input, button, select, body{font-family:Helvetica, 'Microsoft Yahei', verdana}
                        pre {white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space:-o-pre-wrap;word-wrap:break-word;width:95%}
                        th,td{font-family:arial,verdana,sans-serif;line-height:1.666}
                        img{ border:0}
                        header,footer,section,aside,article,nav,hgroup,figure,figcaption{display:block}
                        blockquote{margin-right:0px}
                    </style>
                </head>
                <body tabindex="0" role="listitem">
                <table width="700" border="0" align="center" cellspacing="0" style="width:700px;">
                    <tbody>
                    <tr>
                        <td>
                            <div style="width:700px;margin:0 auto;border-bottom:1px solid #ccc;margin-bottom:30px;">
                                <table border="0" cellpadding="0" cellspacing="0" width="700" height="39" style="font:12px Tahoma, Arial, 宋体;">
                                    <tbody><tr><td width="210"></td></tr></tbody>
                                </table>
                            </div>
                            <div style="width:680px;padding:0 10px;margin:0 auto;">
                                <div style="line-height:1.5;font-size:14px;margin-bottom:25px;color:#4d4d4d;">
                                    <strong style="display:block;margin-bottom:15px;">尊敬的用户：<span style="color:#f60;font-size: 16px;"></span>您好！</strong>
                                    <strong style="display:block;margin-bottom:15px;">
                                        您正在进行<span style="color: red">验证</span>操作，请在验证码输入框中输入：<span style="color:#f60;font-size: 24px">"""+code+
                    """
                    </span>，以完成操作。
                                        </strong>
                                    </div>
                                    <div style="margin-bottom:30px;">
                                        <small style="display:block;margin-bottom:20px;font-size:12px;">
                                            <p style="color:#747474;">
                                                注意：此操作可能会修改您的密码、登录邮箱或绑定手机。如非本人操作，请及时登录并修改密码以保证帐户安全
                                                <br>（工作人员不会向你索取此验证码，请勿泄漏！)
                                            </p>
                                        </small>
                                    </div>
                                </div>
                                <div style="width:700px;margin:0 auto;">
                                    <div style="padding:10px 10px 0;border-top:1px solid #ccc;color:#747474;margin-bottom:20px;line-height:1.3em;font-size:12px;">
                                        <p>此为系统邮件，请勿回复<br>
                                            请保管好您的邮箱，避免账号被他人盗用
                                        </p>
                                        <p>pattern科技有限公司</p>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        </tbody>
                    </table>
                    </body>
                    """;
        }
    }

}
